package com.stars.easyms.rest.autoconfigure;

import com.stars.easyms.base.util.FastJsonUtil;
import com.stars.easyms.rest.handler.EasyMsControllerExceptionAdvice;
import com.stars.easyms.rest.handler.EasyMsRequestResponseBodyMethodProcessor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.resource.*;

import javax.servlet.ServletContext;
import javax.validation.Validator;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * spring boot集成spring mvc的配置类
 *
 * @author guoguifang
 * @date 2018-10-19 10:07
 * @since 1.0.0
 */
@Configuration
public class EasyMsWebMvcAutoConfiguration extends WebMvcConfigurationSupport {

    @Bean
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public StringHttpMessageConverter responseBodyStringConverter() {
        return new StringHttpMessageConverter(StandardCharsets.UTF_8);
    }

    @Bean
    public ResourceHttpRequestHandler resourceHttpRequestHandler(ConfigurableWebApplicationContext webApplicationContext) {
        ServletContext servletContext = webApplicationContext.getServletContext();
        Assert.notNull(servletContext, "servletContext can not be null!");
        super.setServletContext(servletContext);
        ResourceHttpRequestHandler resourceHttpRequestHandler = new ResourceHttpRequestHandler();
        List<Resource> locations = new ArrayList<>();
        locations.add(new ServletContextResource(servletContext, "/"));
        locations.add(new ClassPathResource("META-INF/resources"));
        locations.add(new ClassPathResource("resources/"));
        locations.add(new ClassPathResource("static/"));
        locations.add(new ClassPathResource("public/"));
        resourceHttpRequestHandler.setLocations(locations);
        resourceHttpRequestHandler.setApplicationContext(getApplicationContext());
        List<ResourceResolver> resourceResolvers = new ArrayList<>();
        PathResourceResolver resourceResolver = new PathResourceResolver();
        resourceResolver.setAllowedLocations(new ServletContextResource(servletContext, "/"), new ClassPathResource("META-INF/resources"),
                new ClassPathResource("resources/"), new ClassPathResource("static/"), new ClassPathResource("public/"));
        resourceResolvers.add(resourceResolver);
        resourceHttpRequestHandler.setResourceResolvers(resourceResolvers);
        return resourceHttpRequestHandler;
    }

    @Bean
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping(ResourceHttpRequestHandler resourceHttpRequestHandler) {
        SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("/**", resourceHttpRequestHandler);
        simpleUrlHandlerMapping.setUrlMap(map);
        ResourceUrlProvider resourceUrlProvider = new ResourceUrlProvider();
        Map<String, ResourceHttpRequestHandler> handlerMap = new LinkedHashMap<>();
        handlerMap.put("/**", resourceHttpRequestHandler);
        resourceUrlProvider.setHandlerMap(handlerMap);
        simpleUrlHandlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(resourceUrlProvider));
        return simpleUrlHandlerMapping;
    }

    @Bean
    public EasyMsRequestResponseBodyMethodProcessor easyMsRequestResponseBodyMethodProcessor(
            RequestMappingHandlerAdapter requestMappingHandlerAdapter,
            @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager) {
        EasyMsRequestResponseBodyMethodProcessor easyMsRequestResponseBodyMethodProcessor =
                new EasyMsRequestResponseBodyMethodProcessor(requestMappingHandlerAdapter.getMessageConverters(),
                        contentNegotiationManager, null);
        List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers();
        if (returnValueHandlers != null && !returnValueHandlers.isEmpty()) {
            List<HandlerMethodReturnValueHandler> easyMsReturnValueHandlers = new ArrayList<>();
            for (HandlerMethodReturnValueHandler handlerMethodReturnValueHandler : returnValueHandlers) {
                if (handlerMethodReturnValueHandler instanceof RequestResponseBodyMethodProcessor) {
                    easyMsReturnValueHandlers.add(easyMsRequestResponseBodyMethodProcessor);
                }
                easyMsReturnValueHandlers.add(handlerMethodReturnValueHandler);
            }
            requestMappingHandlerAdapter.setReturnValueHandlers(easyMsReturnValueHandlers);
        }
        return easyMsRequestResponseBodyMethodProcessor;
    }

    @Bean
    public EasyMsControllerExceptionAdvice easyMsControllerExceptionAdvice() {
        return new EasyMsControllerExceptionAdvice();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 有先后顺序，String必须在fastJson之前，因为fastJson会格式化String类型造成String格式错误
        converters.add(responseBodyStringConverter());
        converters.add(FastJsonUtil.getFastJsonHttpMessageConverter());
        addDefaultHttpMessageConverters(converters);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}
